<template>
  <div class="box">
    <el-card style="padding: 0">
      <el-row :gutter="20">
        <el-col :span="20">
          <span style="display: flex; align-items: center;font-size: 17px;margin-bottom: 10px">
            <el-button size="large" type="text" @click="back">
              <el-icon><CaretLeft /></el-icon>返回
            </el-button>
            <b style="margin-left: 10px">任务管理 /</b>
            <el-button
              max-width="100px"
              class="task-button"
              size="large"
              type="text"
              @click="popup('task-edit')"
              @click.stop
            >
            {{ perfTask.taskName }} 
            <el-icon style="color:#53a8ff; padding-left: 3px"><Edit /></el-icon>
          </el-button>
          <el-tag color="#4052EC" style="margin-left: 10px">
            {{ taskTypeMap[perfTask.taskType.toString()] || perfTask.taskType }}
          </el-tag>
          </span>
          <div style="margin-left: 60px">
            <span class="right-info">创建人: {{perfTask.creator}}</span>
            <span class="right-info">创建时间: {{ $tools.rTime(perfTask.create_time) }}</span>
            <span class="right-info">最后修改时间: {{ $tools.rTime(perfTask.update_time) }}</span>
            <span class="right-info">任务描述: {{perfTask.desc}}</span>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="projectInfo">
            <el-button @click="clickRun" type="success" size="default">
              <el-icon><CaretRight /></el-icon>执行任务
            </el-button>
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-row :gutter="2" style=" justify-content: flex-end;">
      <el-col :span="4">
        <div class="tree-component">
          <el-input  v-model="filterText" placeholder="请输入场景名称搜索" clearable >
          <template #append>
              <el-button type="primary" @click="searchClick">查询</el-button>
          </template>
          </el-input>
          <el-button
            type="primary"
            style="margin-bottom: 5px;margin-top: 10px;"
            @click="popup('add')"
          >
            <el-icon><Plus /></el-icon>添加场景
          </el-button>
          <el-scrollbar height="calc(100vh - 265px)">
            <el-tree
              v-if="scenceId"
              node-key="id"
              :current-node-key="scenceId"
              class="filter-tree"
              :data="sceneList"
              :props="defaultProps"
              default-expand-all
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <el-scrollbar>
                  <span class="bold-node">
                    {{ node.label }}
                  </span>
                </el-scrollbar>
                <div class="node-content">
                  <span>
                    <a @click="popup('edit',node.data)"> <el-icon style="color: #0d84ff"><Edit /></el-icon> </a>
                    <a @click="delScene(node.data.id)"> <el-icon style="color: #0d84ff;margin-right: 20px"><Delete /></el-icon> </a>
                  </span>
                </div>
              </template>
            </el-tree>
          </el-scrollbar>
        </div>
      </el-col>
      <el-col :span="14" style="background:#ffffff;">
        <div  class="title">
          <div style="display: flex; justify-content: space-between; align-items: center;">
            <span >场景步骤</span>
            <div style="display: flex; gap: 5px">
                <div>
                  <el-tooltip v-if="scenceData.env" class="box-item" effect="dark" content="查看环境信息" placement="top">
                    <el-button type="primary" plain style="margin-right: 3px" @click="clickShowEnv">
                      <el-icon><View /></el-icon>
                    </el-button>
                  </el-tooltip>
                  <el-select clearable v-model="scenceData.env" placeholder="选择环境" style="width: 180px;" no-data-text="暂无数据" >
                    <el-option v-for="item in testEnvs" :key="item.id" :label="item.name" :value="item.id" />
                  </el-select>
                  <el-dialog v-model="showEnv" title="环境变量" top="10px">
                  <el-descriptions border :column="1" label-align>
                    <el-descriptions-item :label="key" v-for="(value, key) in envInfo.debug_global_variable">
                      <template #label>
                        <el-tag color="#E6A23C">debug</el-tag>
                        {{ key }}
                      </template>
                      {{ value }}
                    </el-descriptions-item>
                    <el-descriptions-item :label="key" v-for="(value, key) in envInfo.global_variable">
                      <template #label>
                        <el-tag color="#67C23AFF">global</el-tag>
                        {{ key }}
                      </template>
                      {{ value }}
                    </el-descriptions-item>
                  </el-descriptions>
                  <template #footer>
                    <span class="dialog-footer">
                      <el-button @click="editEnv(envInfo)" type="success" plain>编辑</el-button>
                      <el-button @click="showEnv = false">关闭</el-button>
                    </span>
                  </template>
                </el-dialog>
                </div>
                <el-dropdown trigger="click" placement="right">
                  <el-check-tag :checked="checked1" type="primary" @change="onChange1">
                    <el-icon><Pointer /></el-icon>
                  </el-check-tag>
                  <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="批量禁用" style="color:#626aef" @click="clickOts('stop')">
                          <el-icon><Remove /></el-icon>
                          批量禁用
                        </el-dropdown-item>
                        <el-dropdown-item command="批量启用" style="color:#67C23A" @click="clickOts('start')">
                          <el-icon><SuccessFilled /></el-icon>
                          批量启用
                        </el-dropdown-item>
                        <el-dropdown-item command="批量删除" style="color:#E6A23C" @click="clickOts('delete')">
                          <el-icon><CircleClose /></el-icon>
                          批量删除
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                </el-dropdown>
                <el-tooltip effect="dark" content="批量同步接口" placement="top">
                  <el-check-tag style="color: #e6a23c;background-color: #fdf6ec" type="primary" @click="clickOts('sync')">
                    <el-icon><Refresh /></el-icon>
                  </el-check-tag>
                </el-tooltip>
                <el-tooltip effect="dark" content="保存" placement="top">
                  <el-check-tag style="color: #4052EC;background-color: #ecf5ff" type="primary" @click="clickScenceStep">
                    <el-icon><Document /></el-icon>
                  </el-check-tag>
                </el-tooltip>
                <el-tooltip effect="dark" content="调试场景" placement="top">
                  <el-check-tag style="color: #4CCB7E;background-color: rgba(76, 203, 126, 0.1)" type="primary" @click="debugScence">
                    <el-icon><VideoPlay /></el-icon>
                  </el-check-tag>
                </el-tooltip>
              </div>
          </div>
        </div>
        <perfStep :scenceId="scenceId" :steps="steps" :scenceData="scenceData" @fetch-steps="getTaskScenceStep"></perfStep>
      </el-col>
      <el-col :span="6">
        <configuration></configuration>
      </el-col>
    </el-row>
  </div>
  <!--  新增/修改场景弹窗-->
  <el-dialog  :title="dialogTitle" v-model="dialogVisible"  width="30%" custom-class="class_dialog" :required="true" style="text-align:left" :before-close="clearValidation">
    <el-form :model="sceneForm" :rules="rulesPerf" ref="perfRef">
      <el-form-item label="场景名称"  prop="name" >
        <el-input v-model="sceneForm.name"  maxlength="50" placeholder="请输入场景名称"/>
      </el-form-item>
    </el-form>
    <template #footer>
			<span class="dialog-footer">
				<el-button @click="clearValidation" >取消</el-button>
        <el-button v-if="dialogType==='add'" type="primary" @click="addScene" >确定</el-button>
				<el-button v-else type="primary" @click="editScene" >确定</el-button>
			</span>
		</template>
  </el-dialog>
  <!--  修改任务名称弹窗-->
  <el-dialog  :title="dialogTitle" v-model="dialogVisible1"  width="30%" custom-class="class_dialog" :required="true" style="text-align:left" :before-close="clearValidation">
    <el-form :model="taskForm" :rules="rulesPerf" ref="perfRef">
      <el-form-item label="任务名称"  prop="taskName" >
        <el-input v-model="taskForm.taskName"  maxlength="50" placeholder="请输入任务名称"/>
      </el-form-item>
      <el-form-item label="任务描述" prop="desc">
        <el-input type="textarea" v-model="taskForm.desc" placeholder="请输入备注"/>
      </el-form-item>
    </el-form>
    <template #footer>
			<span class="dialog-footer">
				<el-button @click="clearValidation" >取消</el-button>
				<el-button  type="primary" @click="editTask" >确定</el-button>
			</span>
		</template>
  </el-dialog>
  <!--  批量同步、批量禁用/启用、批量删除弹窗-->
  <el-drawer v-model="otsDlg"  :title="titleOts" :destroy-on-close="true" :show-close="false" @close="handleClose" size="23%">
    <template #default>
			<el-tabs type="card" style="margin-left: 10px">
        <div>
          <el-checkbox size="mini" :indeterminate="isIndeterminate"  v-model="new_task_form.case_checkAll" @change="handleCheckAllChange" style="padding:0px;margin-right:5px;">全选</el-checkbox>
        </div>
        <el-scrollbar height="calc(100vh - 160px)">
					<el-tree
              v-if="typeOts !== 'sync'"
              ref="casetree"
              :data="steps"
              show-checkbox
              :props="defaultProps"
              @check-change="case_check_change"
              node-key="id"
              :default-expand-all="false"
              highlight-current
              empty-text="暂无数据">
						<template #default="{ node, data }">
							<span class="custom-tree-node">
								<div>
                  <el-icon class="step-icon" style="color: #909399">{{ getCardIndex(node.parent, node) }}</el-icon>
                  {{ data.stepInfo.name }}
								</div>
							</span>
						</template>
					</el-tree>
          <el-tree
              v-else
              ref="casetree"
              :data="steps"
              show-checkbox
              :props="defaultProps"
              @check-change="case_check_change"
              node-key="id"
              :default-expand-all="false"
              highlight-current
              empty-text="暂无数据">
						<template #default="{ node, data }">
							<span class="custom-tree-node">
								<div>
                  <el-icon class="step-icon" style="color: #909399">{{ getCardIndex(node.parent, node) }}</el-icon>
                   {{ data.content?.name || '未定义' }}  {{ data.content?.url || '未定义' }}
								</div>
							</span>
						</template>
					</el-tree>
        </el-scrollbar>
			</el-tabs>
			<div class="add-btns">
        <el-button v-if="typeOts==='start'" plain style="margin-right: 20px" type="success" size="mini" @click="makeOts(typeOts)">确认启用</el-button>
        <el-button v-if="typeOts==='stop'" plain style="margin-right: 20px" type="success" size="mini" @click="makeOts(typeOts)">确认禁用</el-button>
        <el-button v-if="typeOts==='delete'" plain style="margin-right: 20px" type="success" size="mini" @click="makeOts(typeOts)">确认删除</el-button>
        <el-button v-if="typeOts==='sync'" plain style="margin-right: 20px" type="success" size="mini" @click="makeOts(typeOts)">确认同步</el-button>
        <el-button plain type="danger" size="mini" @click="handleClose">关闭窗口</el-button>
			</div>
		</template>
  </el-drawer>
</template>

<script >
import {mapMutations, mapState} from "vuex";
import {ElNotification} from "element-plus";
import perfStep from './perfStep.vue'
import configuration from './maskMgrDetail_set.vue'
import {ElMessage, ElMessageBox} from "element-plus";
import { CaretLeft, Edit, CaretRight, Plus, View, Thumb, Remove, SuccessFilled, 
  CircleClose, Refresh, Document, VideoPlay, Delete } from '@element-plus/icons-vue';
export default {
  components: {
    perfStep,
    configuration,
    CaretLeft,
    Edit,
    CaretRight,
    Plus,
    View,
    Thumb,
    Remove,
    SuccessFilled,
    CircleClose,
    Refresh,
    Document,
    VideoPlay,
    Delete
  },
  data() {
    return {
      dialogType: '',
      dialogTitle: '',
      dialogVisible: false,
      dialogVisible1: false,
      steps:[],
      scenceId: '',
      sceneForm: {
        name : '',
        task :'',
      },
      importSetData:null,
      taskForm:{
        taskName: '',
        desc: '',
        update_time: '',
        modifier : '',
      },
      taskTypeMap: {'10': '普通任务', '20': '定时任务'},
      inputDlg: false,
      filterText:'',
      sceneList: [],
      scenceData:'',
      envInfo:{},
      showEnv: false,
      otsDlg:false,
      titleOts: '',
      typeOts:'',
      new_task_form:{
            "case_checkAll":false
        },
      isIndeterminate:false,

    };
  },
 	methods: {
    ...mapMutations(['clearTask', 'checkedTask', 'selectEnv', 'selectEnvInfo']),

    back() {
      window.history.back();
      this.clearTask()
    },

    async getScenes(query) {
     const response = await this.$api.getTaskScences(this.perfTask.id,query)
     if (response.status ===200){
				this.sceneList = response.data;
				if (response.data.length>0){
				  this.scenceId = response.data[0].id
          this.handleNodeClick(response.data[0])
        }
			}
    },

    async addScene() {
      const params = this.sceneForm
      const response = await this.$api.createTaskScence(params);
      if (response.status === 201) {
        this.$message({
          type: 'success',
          message: '添加成功',
          duration: 1000
        });
        this.clearValidation();
        this.getScenes()
      }
    },
    async editScene() {
      const params = this.sceneForm
      const response = await this.$api.updateTaskScence(params.id,params);
      if (response.status === 200) {
        this.$message({
          type: 'success',
          message: '编辑成功',
          duration: 1000
        });
        this.clearValidation();
        this.getScenes()
      }
    },
    delScene(id) {
    this.$confirm('此操作将永久删除该场景, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
      .then(async () => {
        const response = await this.$api.delTaskScence(id)
        if(response.status ===204){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          // 刷新页面
          this.getScenes();
        }
      })
      .catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
  },
    async clickOts(type) {
      this.otsDlg = type;
      switch (type){
        case 'sync':
          this.titleOts = '批量同步接口数据';
          this.typeOts = type;
          const response = await this.$api.getScenceStep(this.scenceId)
          if(response.status ===200){
            this.steps = response.data;
          }
          break;

        case 'delete':
          this.titleOts = '批量删除';
          this.typeOts = type;
          break;

        case 'start':
          this.titleOts = '批量启用';
          this.typeOts = type;
          break;

        case 'stop':
          this.titleOts = '批量禁用';
          this.typeOts = type;
          break;

      };
    },

    handleClose(){
      this.otsDlg = false;
      this.new_task_form.case_checkAll = false;
      this.getTaskScenceStep(this.scenceId);
    },

    popup(type,data) {
      this.dialogType = type;
      // 根据不同的对话框类型设置标题
      switch (type) {
        case 'add':
          this.dialogVisible = true;
          this.dialogTitle = '新增场景';
          this.sceneForm.task = this.perfTask.id;
          break;

        case 'edit':
          this.dialogVisible = true;
          this.dialogTitle = '编辑场景';
          this.sceneForm = {...data};
          this.sceneForm.id = data.id
          break;

        case 'task-edit':
          this.dialogVisible1 = true;
          this.dialogTitle = '编辑任务';
          this.taskForm.taskName = this.perfTask.taskName;
          this.taskForm.desc = this.perfTask.desc;
          break;

        default:
          this.dialogTitle = '';
          break;
      }
    },

    clearValidation() {
      this.dialogVisible = false;
      this.dialogVisible1 = false;
      this.sceneForm = {
        name : '',
        task :'',
      };
      this.taskForm = {
        taskName: '',
        desc: '',
        update_time: '',
        modifier : ''
      }
    },

    handleNodeClick(data) {
      this.scenceId = data.id;
      this.scenceData = data
      this.getTaskScenceStep(this.scenceId)
    },

    searchClick() {
      this.getScenes(this.filterText)
    },

    startEditing() {
      this.inputDlg = true;
      this.$nextTick(() => {
        this.$refs.input.focus();
      })
    },
    cancelEditing() {
    this.inputDlg = false;
  },
    async clickShowEnv() {
			// 获取单个环境信息
			const response = await this.$api.getEnvInfo(this.scenceData.env,this.pro.id);
			if (response.status === 200) {
				this.envInfo = response.data;
			}
			this.showEnv = true;
		},

		editEnv(envInfo) {
			this.showEnv = false;
			this.selectEnvInfo(envInfo);
			this.$router.push({ name: 'testenv' });
		},
    async editTask() {
      const params = this.taskForm
      params.modifier = this.username;
      params.update_time = this.$tools.newTime()
      const response = await this.$api.updatePerformanceTask(this.perfTask.id, params);
      if (response.status === 200) {
        this.$message({
          type: 'success',
          message: '编辑成功',
          duration: 1000
        });
        this.checkedTask(response.data)
        this.clearValidation();
      }
    },

    async getTaskScenceStep(scenceId) {
      const response = await this.$api.getTaskScenceStep(scenceId);
      if (response.status === 200) {
        this.steps = response.data;
      }
    },
  async clickScenceStep(){
    const prams = {...this.scenceData}
    if(prams.env){
      prams.env = [prams.env]
    }else {
      delete prams.env
    }
    await this.$api.updateTaskScence(this.scenceId,prams)
    const  response = await this.$api.batchUpdateScenceStep(this.steps)
    if (response.status === 200) {
        ElNotification({
            duration: 500,
            title: '保存成功',
            type: 'success',
          });
    }
  },
  getCardIndex(parent, node) {
    const index = parent.childNodes.indexOf(node);
    return index + 1;
  },

  case_check_change(node1,node2,node3){//树节点check事件
            let checked_count = 0;//被勾选上的一级节点个数
            let disabled_count = 0;//置灰的一级节点个数
            let indeterminate_flag = false;//有没有一级节点处于半选状态
            //遍历所有一级节点
            for(let i=0;i<this.steps.length;i++){
                if(this.$refs.casetree.getNode(this.steps[i]).disabled==true){
                    disabled_count += 1;//如果有置灰的节点，置灰变量加1
                }
                if(this.$refs.casetree.getNode(this.steps[i]).checked==true){
                    checked_count += 1;//如果有勾选的节点，勾选变量加1
                }
                if(this.$refs.casetree.getNode(this.steps[i]).indeterminate==true){
                    indeterminate_flag = true;//如果有半选的节点，半选变量设为true
                }
            }

            if(checked_count==0){
                this.isIndeterminate = false;
                this.new_task_form.case_checkAll = false;//如果勾选的一级节点数为0，则设置全选按钮样式不为半选样式，全选的值为false

                if(indeterminate_flag==true){//如果下面有半选的，设置全选按钮的样式为半选样式
                    this.isIndeterminate = true;
                    this.new_task_form.case_checkAll = false;
                }

            }
            else if((checked_count+disabled_count)==this.steps.length){//如果树上勾上的和置灰的加起来等于tree上data的长度，设置全选按钮样式不为半选样式，全选值为true
                this.isIndeterminate = false;
                this.new_task_form.case_checkAll = true;

            }
            else{//上面条件不满足，则说明没有全部勾上，设置样式为半选，全选值为false
                this.isIndeterminate = true;
                this.new_task_form.case_checkAll = false;

            }
            return;

        },

  handleCheckAllChange(val) {
    this.isIndeterminate = false; // 设置全选按钮样式不为半选
    if (val) { // 当前值是全选
        for (let i = 0; i < this.steps.length; i++) {
            if (!this.$refs.casetree.getNode(this.steps[i]).disabled) {
                this.$refs.casetree.setChecked(this.steps[i].id, true, true);
            }
        }
    } else { // 当前值不是全选
        this.$refs.casetree.setCheckedKeys([]); // 清空勾选状态
    }
  },

  async makeOts(type){
    const params = {type:type,data:this.$refs.casetree.getCheckedNodes()}
    if (type!=='sync'){
      const response = await this.$api.batchTaskScenceStep(params);
        if (response.status === 200) {
          ElNotification({
              duration: 500,
              title: '批量变更成功',
              type: 'success',
            });
          this.handleClose();
        }}
    else {
      const response = await this.$api.batchSaveApiSetp(this.$refs.casetree.getCheckedNodes());
      if (response.status === 200) {
        ElNotification({
            duration: 500,
            title: '批量同步成功',
            type: 'success',
          });
        this.handleClose();
      }

    }
  },

  async debugScence(){
    this.$message({
      type: 'warning',
      message: '该功能正在规划中，敬请期待',
      duration: 1000
    });
  },

  async clickRun() {
    const params = { taskId: this.perfTask.id, env: this.envId };
    const response = await this.$api.runTask(this.perfTask.id, params);

    if (response.status === 200) {
      ElNotification({
        title: '任务已启动',
        message: '是否点击该弹窗跳转到性能监控页面？',
        type: 'success',
        duration: 50000,
        showClose: true,
        position: 'top-right',
        onClick: () => {
          // 跳转到性能监控页面
          ElMessageBox.confirm(
            '确认跳转到任务性能监控页面。',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'success',
            }).then(() => {
              this.$router.push({ name: 'PerformanceResult-Detail' })
            }).catch(() => {
            });
        }
      });
    }
  }


	},
  computed: {
    ...mapState(['pro','perfTask','envId','testEnvs']),
    defaultProps() {
      return {
        children: 'children',
        label: 'name',
      }
    },
    selectTaskType: {
      get() {
        return this.form.taskType.toString();
      },
      set(value) {
        this.form.taskType = value;
      }
    },
    username() {
			return window.sessionStorage.getItem('username');
		},
	},

  mounted() {

  },

  watch: {

  },
	created() {
    this.getScenes();
    setTimeout(() => {
        this.getTaskScenceStep(this.scenceId);
    }, 500);
  },

};
</script>

<style scoped>
.box{
  padding:5px 5px 5px 5px;
  background:#f5f7f9;
}
.el-icon-caret-right:before {
    padding-right: 3px;
}

.projectInfo{
  justify-content: flex-end;
  align-items: center;
  display: flex;
  height: 85px;
}

.task-button{
  color:black;
  border: none;
  outline: none;
  font-size: 17px;
  padding-left: 5px;
}
.right-info {
  margin-right: 10px;
  font-size: 14px;
}

.tree-component {
  padding: 10px;
  box-shadow: 5px 0 5px rgba(0, 0, 0, 0.06); /* 添加此样式来设置阴影 */
  background:#ffffff;
}
.filter-tree {
  margin-top: 10px;
  padding-right:0px;
}
.tree-component[data-v-1b4274da] {
    width: 300px;
    padding-right: 0px;
    box-shadow: 5px 0 5px rgba(0, 0, 0, 0.06);
}
.node-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 16px;

}
.el-icon {
  margin-left: 10px;
  transition: transform 0.3s ease;
}
.el-icon:hover {
  transform: scale(1.2);
}
.bold-node {
  font-weight: bold;
}
.el-tag {
  color: #ffffff;
  width: 80px;
  height: 30px;
  text-align: center;
  font-size: 13px;
  line-height: 30px;

}

.title {
    padding: 9px;
    border: 1px solid var(--el-card-border-color);
    background-color: #fff;
    overflow: hidden;
}

.el-dropdown-menu__item {
  color: #606266;
  &:hover {
    background-color: #ebf5ff;
  }
}
.add-btns {
	text-align: center;
}

.step-icon {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  width: 24px;
  height: 24px;
  margin-right: 8px;
  font-weight: bold;
}

</style>
